<template>
    <!-- 需要和gridList组件通信  给该组件传入数据 (被选中的分类) -->
    <slot name="a"></slot>
    <slot name="b"></slot>
    <van-sidebar v-model="activeCategory" @change="onChange">
      <van-sidebar-item v-for="item, index in categoryList" :key="index" :title="(item as unknown as string)" />
    </van-sidebar>
    <span>slots.default</span>
</template>

<script setup lang="ts">
  import  type { Ref } from 'vue';
  import { ref,reactive, onMounted,computed, watchEffect } from 'vue';
  import { getCategoryListAPI,getBrandListAPI } from '@/api/product';
  import { showFailToast } from 'vant';
  import { defineProps,defineEmits,defineOptions,defineModel,defineSlots,defineExpose } from 'vue';
  import { useSlots,useAttrs } from 'vue';


  let props = defineProps(['a','b']) // 接受父组件传入的数据
  let emits = defineEmits(['update:modelValue']) // 接受父组件传入的自定义事件
  let module = defineModel("modelValue") // 以v-model传入的数据(以-v-model传入的数据)



  let slots = defineSlots() // 接收父组件传入的插槽内容  => 对应插槽名称替换<slot name=xxx></slot>
  let slots1 = useSlots() // 接收父组件传入的插槽内容
  let slots12 = useAttrs() // 接收父组件传入的属性 (没有通过props属性接受的)
  // defineExpose()

  defineOptions({
    name:'xxx',
    inheritAttrs:false
  })



  console.log(111,module);
  // console.log(222,props);
  console.log(333,emits);
  console.log(444,slots);
  console.log(444,slots1);

  // defineExpose() //当前组件 向外暴露的方法 可以通过组件实例使用 this.$refs.xxx.方法名()


  let activeCategory = ref(0)
  let categoryList = ref([])

  const getActiveCategory = ()=>{
      console.log("组件内暴露方法测试,父组件可以通过ref名获取当前组件,调用方法");
      return  activeCategory.value;
  }

  const onChange = (index:number)=>{
    activeCategory.value = index
    emits('update:modelValue',(categoryList.value[index] as any))
  }

  const getCategoryList = async()=>{
    try{
      let result = await getCategoryListAPI()
      console.log("分类列表请求成功", result);
      categoryList.value = result.data
    }catch(err:any){
      showFailToast(err.message)
    }
  }
  // defineExpose(); //当前组件 向外暴露的方法  可以先通过ref获取组件, 在通过组件实例使用  this.$refs.xxx.方法名()
  defineExpose({
    getActiveCategory,
    categoryList
  })
    
  onMounted(async ()=>{
    await getCategoryList() // 等分类列表请求成功
    // emits("update:a" ,10)
    if(module.value == null){
      activeCategory.value = 0
      emits('update:modelValue',(categoryList.value[0] as any))
    }else{
      var index = categoryList.value.indexOf(module.value as never)

      if(index !=-1){
        activeCategory.value = index
      }else{
        activeCategory.value=0
        emits('update:modelValue',(categoryList.value[0] as any))
      }
    }
    // emits("update:a", 10);
    // emits("update:modelValue", '显卡');
  })
  
</script>

<style lang="scss" scoped>

</style>